//
//  CJSplashAdapter.m
//  CJMobileAdapter
//
//  Created by Jun on 2024/2/28.
//

#import "CJSplashAdapter.h"
#import "CJSplashCustomEvent.h"
#import "CJCommonTool.h"
#import <AnyThinkSDK/AnyThinkSDK.h>
#import "CJATTMBiddingManager.h"
#import "CJAdapterSetup.h"

@interface CJSplashAdapter()

@property (nonatomic, strong) CJSplashCustomEvent *customEvent;
@property (nonatomic, strong) CJSplashAd *splashView;

@end

static CJSplashAdapter *manager = nil;

@implementation CJSplashAdapter

- (instancetype)initWithNetworkCustomInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo {
    if (self = [super init]) {
//        [CJAdapterSetup setupCJSDKWithAppId:@"appid"];
    }
    return self;
}

- (void)loadADWithInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo completion:(void (^)(NSArray<NSDictionary *> *, NSError *))completion {
    NSDictionary *extra = localInfo;
    NSTimeInterval tolerateTimeout = localInfo[kATSplashExtraTolerateTimeoutKey] ? [localInfo[kATSplashExtraTolerateTimeoutKey] doubleValue] : 5.0;
    NSDate *curDate = [NSDate date];
    if (tolerateTimeout > 0) {
        _customEvent = [[CJSplashCustomEvent alloc] initWithInfo:serverInfo localInfo:localInfo];
        _customEvent.requestCompletionBlock = completion;
        _customEvent.delegate = self.customEvent.delegate;
        CJATTMBiddingRequest *request = [[CJATTMBiddingManager sharedInstance] getRequestItemWithUnitID:serverInfo[@"unitid"]];
        if (request) {
            if (request.customObject != nil) { // load secced
                self.splashView = request.customObject;
                self.splashView.delegate = _customEvent;
                [_customEvent trackSplashAdLoaded:self.splashView];
            } else { // fail
                NSError *error = [NSError errorWithDomain:ATADLoadingErrorDomain code:ATAdErrorCodeThirdPartySDKNotImportedProperly userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load splash.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}];
                [_customEvent trackSplashAdLoadFailed:error];
            }
            [[CJATTMBiddingManager sharedInstance] removeRequestItmeWithUnitID:serverInfo[@"unitid"]];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.splashView = [[CJSplashAd alloc] initWithResourceId:serverInfo[@"unitid"] rootViewController:[CJCommonTool currentRootController] customLogoView:[UIView new]];
                self.splashView.delegate = self.customEvent;
                self.customEvent.containerView = extra[kATSplashExtraContainerViewKey];
                [self.splashView loadAdData];
            });
        }
    } else {
        completion(nil, [NSError errorWithDomain:ATADLoadingErrorDomain code:ATAdErrorCodeThirdPartySDKNotImportedProperly userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load splash.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}]);
    }
}

//v 5.7.06 及以上版本中， splash 广告的 load 和 show 方法已经分开了
#if AnyThinkSDKEnvironment
+ (void)showSplash:(ATSplash *)splash localInfo:(NSDictionary*)localInfo delegate:(id<ATSplashDelegate>)delegate {
    CJSplashAd *splashView = splash.customObject;
    if (splashView) {
        UIWindow *window = localInfo[kATSplashExtraWindowKey];
        [splashView showSplashAdToWindow:window];
    }
}
#endif

+(BOOL)adReadyWithCustomObject:(id)customObject info:(NSDictionary*)info {
#if CJMobileAdEnvironment
    CJSplashAd *splashView = customObject;
    return splashView ? true : false;
#endif
    return false;
}

+ (void)bidRequestWithPlacementModel:(ATPlacementModel *)placementModel unitGroupModel:(ATUnitGroupModel *)unitGroupModel info:(NSDictionary *)info completion:(void(^)(ATBidInfo *bidInfo, NSError *error))completion {
    if (NSClassFromString(@"CJADManager") == nil) {
        if (completion != nil) { completion( nil, [NSError errorWithDomain:@"com.ubix.mediation.ios" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Bid request has failed", NSLocalizedFailureReasonErrorKey:@"TianmuSDK is not imported"}]); }
        return;
    }
    [CJADManager openDebugLog];
    [CJADManager configure:info[@"appid"]];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CJATTMBiddingManager *biddingManage = [CJATTMBiddingManager sharedInstance];
        CJATTMBiddingRequest *request = [CJATTMBiddingRequest new];
        request.unitGroup = unitGroupModel;
        request.placementID = placementModel.placementID;
        request.bidCompletion = completion;
        request.unitID = info[@"unitid"];
        request.extraInfo = info;
        request.adType = ESCAdFormatSplash;
        dispatch_async(dispatch_get_main_queue(), ^{
            UIView *bottomView = [UIView new];
            if ([info valueForKey:@"container_view"] && [[info valueForKey:@"container_view"] isKindOfClass:[UIView class]]) {
                bottomView = [info valueForKey:@"container_view"];
            }
            CJSplashAd *splashView = [[CJSplashAd alloc] initWithResourceId:info[@"unitid"] rootViewController:[CJCommonTool currentRootController] customLogoView:bottomView];
            request.customObject = splashView;
            [biddingManage startWithRequestItem:request];
            [splashView loadAdData];
        });
    });
}


+ (void)sendWinnerNotifyWithCustomObject:(id)customObject secondPrice:(NSString*)price userInfo:(NSDictionary<NSString *, NSString *> *)userInfo {
    CJSplashAd *splashAd = (CJSplashAd *)customObject;
    NSLog(@"比价成功");
}

+ (void)sendLossNotifyWithCustomObject:(nonnull id)customObject lossType:(ATBiddingLossType)lossType winPrice:(nonnull NSString *)price userInfo:(NSDictionary *)userInfo {
    NSLog(@"比价失败");
}


@end
